package org.geppeto.eva.notes;

import java.io.*;
import java.util.HashMap;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;

import org.geppeto.eva.synchronizer.InstanceManager;
import org.w3c.dom.*;
import org.xml.sax.*;

//Treba mi JSON jer cu tako spremati presonalized
// http://lemnik.wordpress.com/2009/01/29/an-automated-json-encoder-and-decoder-for-java/

/**
 * @author 
 * Marko Horvat,
 * Miroslav Popovic
 *
 */

//MATIJA Pogledaj moju clasu Repository.java
public class FileManager {
	
	public static String SPEC_TICKET_OFFICE_FILE_NAME = "ticket_office.xml";
	public static String SPEC_MEET_UP_FILE_NAME = "meet_up.xml";
	public static String SPEC_TRASACTION_FILE_NAME = "transaction.xml";
	public static String DIR_PATH_TEMPLATES = "/src/main/java/org/geppeto/eva/eventory";
	public static String DIR_PATH_PERSONALS = "/src/main/java/org/geppeto/eva/eventory/personals";
	public static String DIR_PATH_NOTES = "/src/main/java/org/geppeto/eva/notes";
	//public static String NOTES_FILENAME = "notes.txt";
		
	private String currentDir;
	private String dirTemplates;
	private String dirPersonals;
	private String dirNotes;
	//private String fileName;
	
	//BEGIN Creating singleton object	
	private static FileManager ref;
	private FileManager (){
		this.currentDir = System.getProperty("user.dir");
		//MATIJA ti ces na njega nadodati neku svoju putanju
		//npr "/src/main/java/org/geppeto/eva/notes"
		this.dirTemplates = currentDir + DIR_PATH_TEMPLATES;
		this.dirPersonals = currentDir + DIR_PATH_PERSONALS;
		this.dirNotes = currentDir + DIR_PATH_NOTES; 
        //this.fileName = NOTES_FILENAME;
	};
	
	public static FileManager getFileManager() {
		if (ref == null)
	        // it's ok, we can call this constructor
			ref = new FileManager();
		return ref;
	}
	public Object clone()throws CloneNotSupportedException
	{
		throw new CloneNotSupportedException();

	}
	//END Creating singleton object	

	
	private String createFileIfItDoesntExist(String directoryPath, String fileName, String xmlRoot ){
		try {
			// Check if user directory exists
			File directory = new File(directoryPath);
			if (!directory.exists()) {
				directory.mkdirs();
			}
			File file = new File(directoryPath + "/" + fileName);
			if (!file.exists()){
				file.createNewFile();
				if (xmlRoot != null ){
					DocumentBuilderFactory documentBuilderFactory = 
						DocumentBuilderFactory.newInstance();

					DocumentBuilder documentBuilder = 
						documentBuilderFactory.newDocumentBuilder();

					Document doc = documentBuilder.newDocument();

					Element rootElement = doc.createElement(xmlRoot);
					doc.appendChild(rootElement);

					Source source = new DOMSource(doc);

					//Prepare the output file            
					Result result = new StreamResult(file);

					// Write the DOM document to the file
					Transformer xformer = TransformerFactory.newInstance().newTransformer();
					xformer.transform(source, result);	
				}	        
			}
			return "true";
		} catch (Exception err) {
			return "failed";
		}
	}

	//MATIJA ova funkcija ti je vec gotova
	//trebas napravit fju saveToFile(String text)
	//Zakljucavanje synchronized ili lock
	protected String readFile(String fileName) throws IOException {
		try{
			createFileIfItDoesntExist(this.dirNotes, fileName, null);
			File file = new File(this.dirNotes + "/" + fileName);
			String xmlSpec = "";
			if (file.exists()) {
				FileInputStream fis = new FileInputStream(file);
				DataInputStream in = new DataInputStream(fis);
				BufferedReader br = new BufferedReader(new InputStreamReader(in));
				String add = "";
				while ((add = br.readLine()) != null) {
					xmlSpec += add;
				}
				br.close();
				in.close();
				fis.close();
			}
			return "{\"content\": \"" + xmlSpec + "\"}";
		} catch (Exception ex){
			return "Failed";
		}
	}
	
	protected String saveToFile(String text, String fileName) throws IOException {
		try{
			text = removeNonPrintableChars(text);
			createFileIfItDoesntExist(this.dirNotes, fileName, null);
			File outFile = new File(this.dirNotes + "/" + fileName);
			FileWriter out = new FileWriter(outFile);
			out.write(text);
			out.close();
			return "OK";
		}
		catch (Exception ex){
			return "Failed";		
		}
	}
	/**
	 * Gets rid of the non printable chars in the string   
	 * @param directoryPath is full path to directory
	 * @return null if not success, string that was truncated if success
	 */		
	private String removeNonPrintableChars(String originalString) {
		try {
			String truncated = originalString.replaceAll("\\p{Cntrl}", "");
			return truncated;
		} catch (Exception err) {
			return null;
		}
	} 

	private String deleteFile(String fullFilePath) {
		try {
			File f = new File(fullFilePath);

			// Make sure the file or directory exists and isn't write protected
			if (!f.exists())
				return "failed: no such file or directory: " + fullFilePath;

			if (!f.canWrite())
				return "failed: write protected: " + fullFilePath;

			// If it is a directory, make sure it is empty
			if (f.isDirectory()) {
				String[] files = f.list();
				if (files.length > 0)
					return "failed: directory not empty: " + fullFilePath;
			}

			// Attempt to delete it
			boolean success = f.delete();

			if (!success)
				return "failed: deletion failed";
			else return "success";
		} catch (Exception err) {
			return err.getMessage();
		}
	}




}
